// bt.module({builder: function(bt){
    var j$ = jQuery;

    var clearQuery = document.getElementById("clearQuery");
    var query = document.getElementById("query");
    var myScroll;

    function clearQueryBox(event){
        query.value="";
        clearQuery.style.display="none";
        clearQuery.style.visibility="hidden";
        j$("#search_result").html("");
        if(event)event.preventDefault();
    }

    function handleClearQueryLink (argument) {
        if ( clearQuery ) {
            if ( query.value.length>0 ) {
                clearQuery.style.display = "block";
                clearQuery.style.visibility = "visible";
            }else{
                clearQuery.style.display = "none";
                clearQuery.style.visibility = "hidden";
            }
        }
    }

    clearQuery.addEventListener("mousedown",clearQueryBox,true);
    query.addEventListener("keyup",handleClearQueryLink,false);

    var lookLotteryRules = j$("#lookRules");
    var lotteryRules = j$("#lotteryRules");
    var inviteWeibo = j$("#inviteWeibo");

    lookLotteryRules.on("click", function () {
        j$(this).text() == "收起" ? j$(this).text("展开") : j$(this).text("收起")
        lotteryRules.toggle();
    });

    var next_cursor = 0;
    var arrayInvite = []; // 已选择
    var arrayUsers  = []; // 待邀请

    function getWeiboFollowerApi (cursor, callback) {
        var content = "";
        if ( cursor == -1) {
            j$("#loading").text("没有更多好友了");
            return false;
        }

        j$.ajax({
            type: 'GET',
            url: '/mobile/guide_to_dive/get_sina_friends/?cursor='+cursor,
            dataType: 'json',
            success: function(data){
                j$.each(data.users, function (index, value) {
                    // console.log(value);
                    content += '<li><label for="'+ value.id +
                    '" onclick><img class="avatar" src="'+value.avatar_large+
                    '"><div class="info"><h4>'+ value.screen_name +
                    '</h4></div><input class="checkbox" type="checkbox" id="'+
                    value.id +'" value="'+ value.screen_name +
                    '"><span class="checkbox_flag">邀请</span></label></li>';
                });
                j$("#waitfor_t").show();
                j$(content).appendTo(waitforinvite);
                data.next_cursor === 0 ? next_cursor = -1 : next_cursor = data.next_cursor;

                // console.log(next_cursor);
                result = "Success";
                return callback( result );
            },
            error: function(xhr, type){
                // alert('出错啦!');
                result = "Error";
                return callback( result );
            }
        });
    }

    function loadMoreFollower () {
        var reachBottom = j$(weibo_users).scrollTop() + j$(weibo_users).innerHeight() >= $(this)[0].scrollHeight - 100;
        if ( reachBottom ) {
            // console.log("At bottom!");
            j$(weibo_users).unbind('scroll');
            getWeiboFollowerApi(next_cursor, function () {
                j$(weibo_users).bind('scroll', loadMoreFollower);
                androidScroll();
            });
        }
    }

    function getWeiboFollower () {
        var weibo_users = j$("#weibo_users");
        var weibo = j$("#weibo");
        var waitforinvite = j$("#waitforinvite");
        var choosed_users = j$("#choosed_users");
        var search_result = j$("#search_result");
        var btns  = j$("#btns");
        weibo.show();

        j$(document).scrollTop(btns.offset().top);

        getWeiboFollowerApi(0, function (argument) {
            if ( result == "Success" ) {
                weibo_users.bind('scroll', loadMoreFollower);
                androidScroll();
            }
        });
    }

    function instantSearch ( callback ) {
        var search_input = j$("#query").val();
        // console.log(search_input);
        if ( search_input == "" ) {
            j$("#search_result").html("");
            return false;
        }
        var keyword = encodeURIComponent(search_input);
        var search_result = j$("#search_result");
        // console.log("haha");
        search_result.html("<p>正在搜索中...</p>");
        j$.ajax({
            type: 'GET',
            url: '/mobile/guide_to_dive/get_sina_friends/?q='+keyword,
            dataType: 'json',
            success: function(data){
                search_result.html("");
                if ( data.users.length == 0 ) {
                    // console.log("haha");
                    search_result.html("<p class='bigbang'>没有找到相关用户</p>");
                    return false;
                }
                j$.each(data.users, function (index, value) {
                    // console.log(value);
                    var userInit = j$.inArray(value.screen_name, arrayInvite);
                    // console.log(userInit);
                    if (userInit < 0 ) {
                        search_result.append(
                            '<li><label for="'+ value.id +
                            '" onclick><img class="avatar" src="'+value.avatar_large+
                            '"><div class="info"><h4>'+ value.screen_name +
                            '</h4></div><input class="checkbox"' +
                            ' type="checkbox" id="'+ value.id +
                            '" value="'+ value.screen_name +
                            '"><span class="checkbox_flag">邀请</span></label></li>'
                        );
                    }
                });

                // console.log(next_cursor);
                result = "Success";
                return callback( result );
            },
            error: function(xhr, type){
                // alert('出错啦!');
                result = "Error";
                return callback( result );
            }
        });
    }

    function addToInvited ( target ) {
        target.parents("li").appendTo(choosed_users).hide().fadeIn();
        arrayInvite.push( target.prop("value") );
        if ( arrayInvite.length > 0 ) j$("#already_t").show();
        j$("#already_t").find("span").text(arrayInvite.length);
        // console.log( arrayInvite );
    }

    function removeFromInvited ( target ) {
        target.prop('checked',false).parents("li").prependTo(waitforinvite);
        // console.log(target.prop("name"));
        arrayInvite.pop( target.prop("name") );
        if ( arrayInvite.length == 0 ) j$("#already_t").hide();
        j$("#already_t").find("span").text(arrayInvite.length);
        // console.log("Removed.");
        // console.log( arrayInvite );
    }

    function sendInvite (callback) {
        var form = j$("#choosed_users_form");
        j$("#post_value").attr("value", arrayInvite);
        var args = form.serialize();
        if ( arrayInvite == "" ) { return false; }
        j$.ajax({
            type: 'POST',
            url: form.attr("action"),
            data: args,
            success: function(data){
                // alert("发送成功");
                result = "Success";
                return callback( result );
            },
            error: function(xhr, type){
                // alert('出错啦!');
                result = "Error";
                return callback( result );
            }
        });
    }

    function hideUpdatePopup() {
        j$(".download-popup").hide();
        j$(".overlay").hide();
    }

    function showUpdatePopup(text, cancel_text, ok_text) {
        if(cancel_text) {
            j$(".download-popup .cancel").text(cancel_text);
        }
        if(ok_text) {
            j$(".download-popup .ok").text(ok_text);
        }
        if(text) {
            // console.log(text)
            j$(".download-popup .content").text(text);
        }
        j$(".overlay").show();
        j$(".download-popup").show();
    }

    function jumpAdduser(user_agent) {
        if(user_agent == 1) {
            // console.log(version);
            if(version < "2.2.0") {
                showUpdatePopup("您的面包旅行APP版本较低，暂不支持此次邀请活动，请升级最新版后再参加活动。立即去升级？", "忽略");
            } else {
                if(version < "2.2.1") {
                    showUpdatePopup("您的面包旅行APP版本较低，无法直接跳转至微信邀请页面。请去“找朋友”页面邀请好友或直接升级。");
                } else {
                    window.location.href= "app:jump:adduser";
                }
            }
        }
        if(user_agent == 4) {
            if(typeof android == "undefined") {
                showUpdatePopup("您的面包旅行APP版本较低，无法直接跳转至微信邀请页面。请升级后，参加此次邀请活动，并获得更好的使用体验。");
            } else {
                android.startFindFriendActivity();
            }
        }
    }

    function modifyCount (obj, count, re1, re2){
        if(!obj || !obj.html()) {
            return;
        }
        var count = count || 1;
        var re1 = /[\d]/
        var re2 = /[^\d]+/g;
        var old_strings = obj.html().split(re1);
        var num = parseInt(obj.html().replace(re2, ''));
        old_strings.splice(1, 0, num + count);
        var t = old_strings.join('');
        obj.html(old_strings.join(''));
    }

    function verifyUser (callback) {
        return;
        var form = j$("#form_verify");
        var error = j$("#verify_error");
        error.text("");
        // j$("#post_value").attr("value", arrayInvite);
        var args = form.serialize();
        j$.ajax({
            type: 'POST',
            url: form.attr("action"),
            data: args,
            success: function(data){
                if ( data.success ) {
                    j$("#invited").prepend(
                            '<li><img class="avatar" src="' + data.invitee.avatar_l +
                            '"><div class="info"><h4>'+ data.invitee.name +
                            '</h4><p>抽奖号码：<br>'+ data.lottery_code +'</p>' +
                                '</div></li>');
                    modifyCount(j$(".verify h3 span"), 1);
                }else{
                    error.text(data.msg);
                }
                result = "Success";
                return callback( result );
            },
            error: function(xhr, type){
                // alert('出错啦!');
                result = "Error";
                return callback( result );
            },
            complete: function (argument) {
                j$("#btn_verify").delegate("click");
            }
        });
    }

    j$("#weibo_users_wrap .checkbox").live('change', function() {
        if ( this.checked ) {
            addToInvited( j$(this) );
        } else {
            removeFromInvited( j$(this) );
        }
    });

    j$("#search_result .checkbox").live('change', function() {
        var Id = j$(this).attr("id");
        if ( this.checked ) {
            j$(waitforinvite).find('#'+Id).parents("li").remove();
            addToInvited( j$(this) );
        } else {
            var target = j$(choosed_users).find('#'+Id);
            removeFromInvited( target );
        }
    });

    inviteWeibo.one("click", function (e) {
        bt.sns.checkConnection(function(resp) {
            if(!resp.sina) {
                bt.sns.connect("sina", {
                    callback_method_name: "/mobile/guide_to_dive/?expend_sina_panel=1",
                    window_open: false
                });
            }else{
                getWeiboFollower();
            }
        });
    });

    j$("#btn_sent").on("click", function ( ) {
        // console.log(arrayInvite);
        sendInvite(function () {
            if ( result == "Success" ) {
                var alertBox = "<div class='alertBox'><img width='25' height='20' src='/static/img/dive_icon_mail.png' alt='' />发送邀请成功!</div>";
                var width = j$("section").width();
                j$(alertBox).appendTo("body").show();
                setTimeout(function () {
                    window.location = "/mobile/guide_to_dive/?expend_sina_panel=1";
                }, 3000);
            }
        });
    });

    j$("#btn_verify").on("click", function () {
        j$(this).undelegate("click");
        verifyUser(function(){});
    });

    j$("#form_verify").on("submit", function (e) {
        e.preventDefault();
        verifyUser(function(){});
    });

    j$("#more").on("click", function () {
        j$(this).text() == "查看更多" ? j$(this).text("收起") : j$(this).text("查看更多")
        j$("#invited").toggleClass("invited_more");
    });

    // Android version < 3
    function androidScroll (argument) {
        var ua = navigator.userAgent.indexOf("Android ");
        // var majorversion = navigator.userAgent.substr(ua+8,1);
            // alert("yeah");
        if ( ua > 0 ) {
            // alert("android");
            var myScroll = new iScroll('weibo_users', {
                onScrollEnd: function () {
                    getWeiboFollowerApi(next_cursor, function () {
                        j$(weibo_users).bind('scroll', loadMoreFollower);
                        myScroll.refresh();
                    });
                }
            });
            myScroll.refresh();
        }
    }

    j$("#weibo form").submit(function (e) {
        e.preventDefault();
        j$("#query").blur();
    });

    j$("#query").keyup(function () {
        instantSearch(function(){
            // console.log(weibo_users);
            j$("#weibo_users").animate({scrollTop: 0});
        });
    });

    var j$ = jQuery;
    var type, version;
    var appVersion = j$("body").data("version").split("_", 2);
    type = appVersion[0];
    version = appVersion[1];

    j$(".cancel").live("click", function() {
        hideUpdatePopup();
    });


// }});
